前后端分离时,JQuery使用Post出现400和415错误 |
您所在的位置:网站首页 › 错误代码 415 › 前后端分离时,JQuery使用Post出现400和415错误 |
目录
后端接口介绍前端ajax出现415错误出现400错误解决方法
后端接口介绍
采用前后端分离的结构,后端是一个post接口: @PostMapping("/blog/edit") public Result edit(@Validated @RequestBody Blog blog) {Blog需要传三个参数: titledescriptioncontent 前端ajax要传输的数据: var blogJsonData = { "title":"测试3444", "description":"描述描述描述333333", "content":"contents333" }; 出现415错误使用的是这个代码(曾经没有前后端分离时的某个小项目中用过) $.post("http://localhost:8081/blog/edit", blogJsonData, function(result){ console.dir(result);//在控制台打印结果 },"json");但是报错: 于是去W3school中看ajax()方法的介绍(本人小白,编程不太熟练),找能够添加消息请求类型的代码。 然后用的是这个: jQuery.ajax({ type: "post", dataType: "json", url: "http://localhost:8081/blog/edit", contentType: "application/json;charset=UTF-8",//指定消息请求类型 data: blogJsonData, success: function (result) { console.dir(result);//在控制台打印结果 } });但是报错: 再次搜索400问题的解决方法,判断可能是传输数据的问题: 上面传的是json对象,需要传输json对象的字符串形式。于是在jQuery.ajax前面添加了一句:blogJsonData = JSON.stringify(blogJsonData),得到: var blogJsonData = { "title":"测试3444", "description":"描述描述描述333333", "content":"contents333" }; blogJsonData = JSON.stringify(blogJsonData);//需要变成字符串格式 jQuery.ajax({ type: "post", dataType: "json", url: "http://localhost:8081/blog/edit", contentType: "application/json;charset=UTF-8",//指定消息请求类型 data: blogJsonData, success: function (result) { console.dir(result);//在控制台打印结果 } });最终成功访问到后端的数据。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |